"""
百度千帆API鉴权模块
"""
import requests
import time
from django.conf import settings
from django.core.cache import cache
import logging

logger = logging.getLogger(__name__)


class BaiduAuthManager:
    """百度API鉴权管理器"""
    
    def __init__(self):
        self.config = settings.BAIDU_QIANFAN_CONFIG
        self.api_key = self.config['API_KEY']
        self.secret_key = self.config['SECRET_KEY']
        self.token_url = self.config['TOKEN_URL']
        self.cache_timeout = self.config['CACHE_TIMEOUT']
        self.cache_key = 'baidu_access_token'
    
    def get_access_token(self):
        """
        获取百度API访问令牌
        先从缓存获取，如果没有或过期则重新请求
        """
        # 尝试从缓存获取token
        token_data = cache.get(self.cache_key)
        if token_data:
            logger.info("从缓存获取到百度Access Token")
            return token_data['access_token']
        
        # 缓存中没有token，重新请求
        return self._request_new_token()
    
    def _request_new_token(self):
        """请求新的访问令牌"""
        try:
            params = {
                'grant_type': 'client_credentials',
                'client_id': self.api_key,
                'client_secret': self.secret_key
            }
            
            logger.info("正在请求百度Access Token...")
            response = requests.get(self.token_url, params=params, timeout=30)
            response.raise_for_status()
            
            data = response.json()
            
            if 'access_token' in data:
                # 获取token成功，存入缓存
                token_data = {
                    'access_token': data['access_token'],
                    'expires_in': data.get('expires_in', 2592000),  # 默认30天
                    'created_at': time.time()
                }
                
                # 提前5分钟过期，避免边界情况
                cache_timeout = token_data['expires_in'] - 300
                cache.set(self.cache_key, token_data, timeout=cache_timeout)
                
                logger.info(f"成功获取百度Access Token，有效期: {token_data['expires_in']}秒")
                return data['access_token']
            else:
                error_msg = data.get('error_description', '未知错误')
                logger.error(f"获取百度Access Token失败: {error_msg}")
                raise Exception(f"获取Access Token失败: {error_msg}")
                
        except requests.RequestException as e:
            logger.error(f"请求百度Access Token时网络错误: {str(e)}")
            raise Exception(f"网络请求失败: {str(e)}")
        except Exception as e:
            logger.error(f"获取百度Access Token时发生错误: {str(e)}")
            raise
    
    def clear_token_cache(self):
        """清除token缓存"""
        cache.delete(self.cache_key)
        logger.info("已清除百度Access Token缓存")


# 创建全局实例
baidu_auth = BaiduAuthManager()